import {Injectable} from '@angular/core';
import {
  HttpErrorResponse,
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
  HttpResponse
} from '@angular/common/http';
import {Observable} from 'rxjs';
import {tap} from 'rxjs/operators';
import {Router} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd';
import {removeToken} from '../../util/token.util';

/**
 * 接口错误统一处理
 */
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {

  constructor(private router: Router, private message: NzMessageService) {
  }

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request).pipe(tap(response => {
        if (response instanceof HttpResponse) {
          if (response.status === 200 && response.body) {
            if (response.body.exceptionMessage) {
              this.message.error(response.body.exceptionMessage);
            }

            // token 失效
            // this.router.navigate(['/login']);
          }
        }
      }, error => {
        if (error instanceof HttpErrorResponse) {
          if (error.status === 403 || error.status === 401) {
            removeToken();
            this.message.error('身份已过期，请重新登陆');
          } else if (error.status >= 500) {
            this.message.error(`服务器内部错误 ${error.status}`);
          } else if (error.status >= 400 && error.status < 500) {
            this.message.error(`客户端参数错误 ${error.status}`);
          }
        }
      }
      )
    );
  }
}
